import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

import java.awt.*;
import java.util.Map;

/**
 * Created by Administrator on 2016/3/3.
 */
public class MyBarChartPanel extends ChartPanel {
    public MyBarChartPanel(String title,String titleX,String titleY, Dimension dimension,Map<String,Object> data) {
        super(createChart(title,titleX,titleY,createDataset(data)));
        this.setSize(dimension);
        this.setPreferredSize(dimension);
    }

    public static CategoryDataset createDataset(Map<String,Object> data) //创建柱状图数据集
    {
        DefaultCategoryDataset dataset=new DefaultCategoryDataset();
        for (String key : data.keySet()) {
            Object value = data.get(key);
            dataset.setValue(Double.parseDouble(value.toString()),key,key);
            // System.out.println("Key = " + key + ", Value = " + value);

        }
//        dataset.setValue(10,"a","管理人员");
//        dataset.setValue(20,"b","市场人员");
//        dataset.setValue(40,"c","开发人员");
//        dataset.setValue(15,"d","其他人员");
        return dataset;
    }

    public static JFreeChart createChart(String title,String titleX,String titleY,CategoryDataset dataset) //用数据集创建一个图表
    {
        //创建主题样式
        StandardChartTheme standardChartTheme=new StandardChartTheme("CN");
        //设置标题字体
        standardChartTheme.setExtraLargeFont(new Font("隶书",Font.BOLD,12));
        //设置图例的字体
        standardChartTheme.setRegularFont(new Font("宋书",Font.PLAIN,10));
        //设置轴向的字体
        standardChartTheme.setLargeFont(new Font("宋书",Font.PLAIN,10));
        //应用主题样式
        ChartFactory.setChartTheme(standardChartTheme);

        JFreeChart chart= ChartFactory.createBarChart("hi", titleX,
                titleY, dataset, PlotOrientation.VERTICAL, false, true, false); //创建一个JFreeChart
        chart.setTitle(new TextTitle(title,new Font("宋体",Font.BOLD+Font.ITALIC,20)));//可以重新设置标题，替换“hi”标题
        CategoryPlot plot=(CategoryPlot)chart.getPlot();//获得图标中间部分，即plot
        CategoryAxis categoryAxis=plot.getDomainAxis();//获得横坐标
        categoryAxis.setLabelFont(new Font("微软雅黑",Font.BOLD,10));//设置横坐标字体

        ValueAxis valueAxis=plot.getRangeAxis();//获得纵坐标
        valueAxis.setLabelFont(new Font("微软雅黑",Font.BOLD,10));//设置纵坐标字体
        plot.setNoDataMessage("No data available");


        return chart;
    }


}
